package com.sui.bigdata.rtcadmin.show;

import com.feidee.fdcommon.util.ToolUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author YongChen
 * @date 2020/2/28 15:48
 * @description
 * @email yong_chen@sui.com
 */

@ServerEndpoint(value = "/job/select/res/{eid}")
@Component
@Slf4j
public class SelectResServer {

    private Session session;
    private String eid;

    /**
     * 保存每个客户端的 WebSocket 连接对象
     */
    private static CopyOnWriteArraySet<SelectResClient> clients = new CopyOnWriteArraySet<>();

    @OnOpen
    public void onOpen(Session session, @PathParam("eid") String eid) {
        this.eid = eid;
        this.session = session;
        if (!ToolUtils.isNotNull(eid)) {
            throw new RuntimeException("eid is null");
        }
        SelectResClient client = new SelectResClient(eid, session);
        clients.add(client);
        log.debug("{} 开始监控任务【{}】的运行状态", session.getId(), eid);
    }

    @OnClose
    public void onClose() {
        clients.forEach(client -> {
            if (client.getSession() == session) {
                clients.remove(client);
            }
        });
        log.debug("{} 结束对任务【{}】运行状态的监听", session.getId(), eid);
    }

    @OnMessage
    public void onMessage(String message) {
        log.debug("任务 {} 运行状态发生改变, {}", eid, message);
    }

    @OnError
    public void onError(Throwable e) {
        log.error(session.getId() + " 监听任务【" + eid + "】状态失败", e);
    }

    public void sendMessageToAll(String message) {
        log.debug("【监听运行状态】发送全局消息：{}", message);
        clients.forEach(client -> {
            try {
                client.getSession().getBasicRemote().sendText(message);
            } catch (IOException e) {
                log.error("【监听运行状态】全局消息时发生错误，连接 id " + client.getSession().getId(), e);
            }
        });
    }

    public synchronized static void sendMessage(String message, String eid) {
        if (!ToolUtils.isNotNull(eid)) {
            throw new RuntimeException("任务名称不能为空");
        }
        clients.forEach(client -> {
            if (client.getEid().equals(eid)) {
                try {
                    client.getSession().getBasicRemote().sendText(message);
                } catch (IOException e) {
                    log.error("发送任务结果给连接 id " + client.getSession().getId() + " 时发生错误", e);
                }
            }
        });
    }

    public static void closeClient(String eid) {
        log.debug("【监听运行状态】关闭对任务 {} 的 websocket 连接", eid);
        clients.forEach(client -> {
            if (client.getEid().equals(eid)) {
                try {
                    client.getSession().close();
                    clients.remove(client);
                } catch (IOException e) {
                    log.error("关闭对任务 " + eid + " 的状态监听失败", e);
                }
            }
        });
    }

    public static void closeAllClients() {
        log.debug("【监听运行状态】关闭所有本机 websocket 连接");
        clients.forEach(client -> {
            try {
                client.getSession().close();
                clients.remove(client);
            } catch (IOException e) {
                log.error("全局关闭实验监听连接时发生错误，连接 id" + client.getSession().getId(), e);
            }
        });
    }
}
